<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px" @keyup.enter="submitHandle()">
			<el-form-item label="课程名称" prop="name">
				<el-input v-model="dataForm.name"></el-input>
			</el-form-item>
      <el-form-item label="课程类型" prop="type">
        <el-select v-model="dataForm.type">
          <el-option label="必修课" :value="1"></el-option>
          <el-option label="专业课" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属专业" prop="specializedId" v-if="dataForm.type === 2">
        <el-select v-model="dataForm.specializedId">
          <el-option v-for="item in speList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {useCouSubmitApi, useGetCouInfoApi} from "@/api/college/cou";
import {useSpeSelectApi} from "@/api/college/spe";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const speList = ref<any>([])
const dataFormRef = ref()

const dataForm = reactive({
	id: '',
	name: "",
  type: 2,
  specializedId: ""
})

const init = (id?: string) => {
	visible.value = true
	dataForm.id = ''

  dataFormRef.value?.resetFields()

	// 存在则为修改
	if (id) {
    useGetCouInfoApi(id).then(res=>{
      Object.assign(dataForm, res.data)
    })

	}

  getSpeList()
}

function getSpeList(){
  useSpeSelectApi().then(res=>{
    speList.value = res.data
  })
}

const dataRules = ref({
	name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	type: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
  specializedId: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

    useCouSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
